package com.to8to.autotask.server;

import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.elasticsearch.common.base.Function;
import org.elasticsearch.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.autotask.deduction.ForfeitDeductTask;
import com.to8to.autotask.resulthandler.FailHandler;
import com.to8to.autotask.scheduler.AutoTaskScheduler;
import com.to8to.autotask.util.Constant;
import com.to8to.autotask.util.Utils;
import com.to8to.crm.common.DefaultDeamon;
import com.to8to.es.util.LogUtil;
import com.to8to.kitt.esb.NodeChangeEvent;

/**
 * DeamonWithCronScheduler.java
 * 作 者：atom.liu
 * 版 本：v2.0
 * 日 期：2015年1月13日
 * 描 述：包含处理定时任务配置的Deamon
 */
public class DeamonWithTaskProperty extends DefaultDeamon
{
    private static final Logger logger = LoggerFactory.getLogger(DeamonWithTaskProperty.class);

    /**
     * 任务调度配置
     */
    private static final String CRON4J_CONF_PATH = "cron4j.properties";

    /**
     * 分配审核客服时，不需要考虑重复项目的手机号
     */
    private static final String TASK_PROP = "task.properties";

    /**
     * 私有配置发生改变时触发的回调函数
     */
    @Override
    public void onPrivateConfigChange(Map<String, NodeChangeEvent> configMap)
    {
        if (Utils.isNullOrEmpty(configMap))
            return;

        String[] files = new String[] { CRON4J_CONF_PATH, TASK_PROP, deamonFile };
        for (String file : files)
        {
            NodeChangeEvent event = configMap.get(file);
            if (event == null || !event.isChange())
            {
                if (event == null)
                    logger.error("Can't find " + file);
                continue;
            }

            if (CRON4J_CONF_PATH.equals(file))
            {
                byte[] data = event.ndata;
                try
                {
                    PropertiesConfiguration prop = new PropertiesConfiguration();
                    prop.load(new ByteArrayInputStream(data));
                    Map<String, String> map = Maps.toMap(prop.getKeys(), new Function<String, String>()
                    {
                        @Override
                        public String apply(String key)
                        {
                            return prop.getString(key);
                        }
                    });
                    AutoTaskScheduler.addSchedulerTask(map);
                }
                catch (ConfigurationException e)
                {
                    logger.error("DeamonWithCronScheduler.onPrivateConfigChange() 加载配置失败！{} \n {}", e, LogUtil.logStackTrace(e));
                }
            }
            else if (TASK_PROP.equals(file))
            {
                byte[] data = event.ndata;
                try
                {
                    PropertiesConfiguration prop = new PropertiesConfiguration();
                    prop.load(new ByteArrayInputStream(data));
                    String[] phones = prop.getStringArray("ignore_repeat_phone");
                    String[] noticeEmails = prop.getStringArray("fail_notic_email");
                    Map<String, List<String>> forfeitMap = Maps.newHashMap();
                    forfeitMap.put("not_cost_uid", Arrays.asList(prop.getStringArray("not_cost_uid")));
                    forfeitMap.put("not_cost_yid", Arrays.asList(prop.getStringArray("not_cost_yid")));
                    forfeitMap.put("not_cost_city", Arrays.asList(prop.getStringArray("not_cost_city")));
                    forfeitMap.put("new_not_cost_city", Arrays.asList(prop.getStringArray("new_not_cost_city")));
                    forfeitMap.put("need_cost_uid", Arrays.asList(prop.getStringArray("need_cost_uid")));
                    Map<String, List<String>> channelMap = Maps.newHashMap();
                    channelMap.put("h5", Arrays.asList(prop.getStringArray("h5")));
                    channelMap.put("pc", Arrays.asList(prop.getStringArray("pc")));
                    FailHandler.initNoticeEmail(noticeEmails);
                    ForfeitDeductTask.initConfig(forfeitMap);
                    Constant.initIgnoreRepeatPhone(phones);
                    Constant.initChannelInfo(channelMap);
                    Constant.initSpecCityInfo(prop.getStringArray("spec_city"));
                }
                catch (ConfigurationException e)
                {
                    logger.error("AutoTaskServer.onPrivateConfigChange() 加载配置失败！{} \n {}", e, LogUtil.logStackTrace(e));
                }
            }
            else if (deamonFile.equals(file))
            {
                super.onPrivateConfigChange(configMap);
            }
        }
    }
}
